package com.lishe.lishe.lishe.module.excitation.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.lishe.lishe.Imageloader.ImageLoaderUtils;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.base.BaseApplication;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.http.HttpUser;
import com.lishe.lishe.lishe.module.excitation.adapter.StringAdapter;
import com.lishe.lishe.lishe.module.excitation.bean.company.CompanyInfo;
import com.lishe.lishe.lishe.module.excitation.bean.company.JoinCompany;
import com.lishe.lishe.lishe.module.excitation.bean.user.UserObject;
import com.lishe.lishe.lishe.module.excitation.presenter.ExcitationPresenter;
import com.lishe.lishe.lishe.module.main.activity.MainActivity0;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.SharedPreferencesUtils;
import com.lishe.lishe.lishe.widget.ConfirmDialog;
import com.lishe.lishe.lishe.widget.MListDialog;
import com.lishe.lishe.retrofit.DataResponseListener;
import com.lishe.lishe.retrofit.bean.InfoArrayObject;
import com.lishe.lishe.retrofit.bean.InfoObject;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by shino on 2017/12/21.
 * 确认企业
 */

public class CompanyConfirmActivity extends BaseActivity implements View.OnClickListener {

    private Button callBack;
    private Button moreButton;
    private Button confirm;
    private TextView title;
    private String comID;
    private int type = 1;//类型： 1：离职，2：退出

    private TextView company;
    private TextView name;
    private TextView job;
    private ImageView headerImage;
    private ImageView logo;

    private ImageLoaderUtils imageLoaderUtils;

    private boolean isLoading = false;//登录
    private UserObject userObject = null;
    private List<CompanyInfo> companys = new ArrayList<>();
    private boolean isOut;//是否退出应用

    public static void jump(Activity activity, String comID, boolean isOut) {
        Intent intent = new Intent(activity, CompanyConfirmActivity.class);
        intent.putExtra("comID", comID);
        intent.putExtra("isOut", isOut);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_company_confirm);
        comID = getIntent().getStringExtra("comID");
        isOut = getIntent().getBooleanExtra("isOut", false);
        imageLoaderUtils = new ImageLoaderUtils();
        imageLoaderUtils.setOptionsImage(R.mipmap.head);
        initView();
    }

    private void initView() {
        callBack = findViewById(R.id.title_left_button);
        moreButton = findViewById(R.id.more_button);
        moreButton.setVisibility(View.VISIBLE);
        title = findViewById(R.id.title_text_title);
        title.setText("确认企业");
        confirm = findViewById(R.id.confirm);
        company = findViewById(R.id.company);
        name = findViewById(R.id.name);
        job = findViewById(R.id.job);
        headerImage = findViewById(R.id.header_image);
        logo = findViewById(R.id.logo);
        setListener();
    }

    /**
     * 数据初始化
     */
    private void initData(UserObject userObject) {
        if (userObject == null || userObject.getComId().equals("-1")) {//未加入企业
            logo.setVisibility(View.GONE);
        } else {
            comID = userObject.getComId();
            company.setText(userObject.getComName());
            name.setText(userObject.getEmpName());
            String str = "";
            if (!TextUtils.isEmpty(userObject.getDeptName())) {
                str = userObject.getDeptName();
            }
            if (!TextUtils.isEmpty(userObject.getPosName())) {
                if (str.length() > 0) {
                    str = str + "·";
                }
                str = str + userObject.getPosName();
            }
            job.setText(str);
            if (!TextUtils.isEmpty(userObject.getUserAvatarPath())) {
                imageLoaderUtils.displayImage(userObject.getUserAvatarPath(), headerImage);
            }
            company.setText(userObject.getComName());

            if (userObject.getComStatus().equals("1")) {
                logo.setVisibility(View.VISIBLE);
            } else {
                logo.setVisibility(View.GONE);
            }
        }
    }

    private void setListener() {
        callBack.setOnClickListener(this);
        moreButton.setOnClickListener(this);
        confirm.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left_button:
                if (isOut) {
                    Intent intent = new Intent(Globals.ACTION_FINISH_ALL_ACTIVITY);
                    sendBroadcast(intent);
                } else {
                    finish();
                }
                break;
            case R.id.confirm://进入企业
                if (TextUtils.isEmpty(comID)) {
                    toast("公司ID不能为空！");
                    return;
                }
                isLoading = true;
                upToken(comID);
                break;
            case R.id.more_button://右上角更多
                createDialog();
                break;
        }
    }

    List<String> list = new ArrayList<>();
    private void createDialog() {
        list.clear();
        if (userObject != null) {
            if (userObject.getEmpStatus().equals("-1")) {//未确认
                list.add("这不是我的企业，退出");
            } else {
                list.add("我已从这家公司离职，退出");
                list.add("这不是我的企业，退出");
            }
        } else {
            list.add("我已从这家公司离职，退出");
            list.add("这不是我的企业，退出");
        }
        StringAdapter adapter = new StringAdapter(list);
        final MListDialog.Builder dialog = new MListDialog.Builder(context);
        dialog.setAdapter(adapter);
        dialog.create().show();
        dialog.getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.e("点击", list.get(position));
                dialog.dissmiss();
                String str = "";
                String title = "";
                if (position == 0) {//我已从这家公司离职，退出
                    type = 1;
                    str = "离职退出后,您将无法进入企业，重新进入企业需要联系企业管理员。";
                    title = "是否从企业离职";
                }
                if (position == 1) {//这不是我的企业，退出
                    type = 2;
                    str = "退出后,您将无法进入企业，重新进入企业需要联系企业管理员。";
                    title = "是否退出企业";
                }
                createCustomDialog(str, title);
            }
        });

    }

    private void createCustomDialog(String content, String title) {
        ConfirmDialog.Builder confirmDialog = new ConfirmDialog.Builder(this);
        confirmDialog.setTitle(title);
        confirmDialog.setContent(content);
        confirmDialog.setPositiveButtonColor(R.color.color4138);
        confirmDialog.setOnNegativeListener(new ConfirmDialog.Builder.OnNegativeListener() {
            @Override
            public void onNegative(ConfirmDialog dialog) {
                dialog.dismiss();
            }
        });
        confirmDialog.setPositiveButton("退出", new ConfirmDialog.Builder.OnPositiveListener() {
            @Override
            public void onPositive(ConfirmDialog dialog) {
                dialog.dismiss();
                signOut();
            }
        });
        confirmDialog.show();
    }

    /**
     * 登陆企业后更新token
     */
    private void upToken(String comId) {
        String token = Globals.getToken();
        LoadingUtils.createLoadingDialog(this, "正在登录", true);
        HttpUser.getUpToken(token, comId, responseHandler);
    }

    AsyncHttpResponseHandler responseHandler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String data = new String(responseBody);
            LoadingUtils.closeDialog();

            if (data != null) {
                try {
                    String msg = "";
                    JSONObject jsonObject = new JSONObject(data);
                    if (jsonObject.optInt("errcode") == 0 && jsonObject.optInt("result") == 100) {
                        finish();
                        String mtoken = jsonObject.optString("data");
                        if (!TextUtils.isEmpty(mtoken) && !mtoken.equals("null")) {
                            SharedPreferencesUtils.saveToken(mtoken, CompanyConfirmActivity.this);
                        }

                        if (isLoading) {
                            Intent intent = new Intent(Globals.ACTION_FINISH_ALL_ACTIVITY);
                            getApplicationContext().sendBroadcast(intent);
                            MainActivity0.jump(CompanyConfirmActivity.this, 1);
                        } else {
//                            toast("成功退出企业！");
                        }
                        finish();
                    } else {
                        toast(msg);
                    }
                } catch (JSONException e) {
                    LoadingUtils.closeDialog();
                    e.printStackTrace();
                }
            }

        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            toast("企业登录失败！");
            LoadingUtils.closeDialog();
        }
    };

    //登出企业或离职
    private void signOut() {
        if (TextUtils.isEmpty(comID)) {
            toast("公司ID不能为空！");
            return;
        }
        String messg = "正在退出企业...";
        if (type == 1) {
            messg = "离职办理中...";
        }

        LoadingUtils.createLoadingDialog(this, messg, true);
        ExcitationPresenter.getInstance().userQuitCom(Globals.getToken(), type + "", comID, new DataResponseListener<String>() {
            @Override
            public void onSuccess(String dataResponse) {
                LoadingUtils.closeDialog();
                if (dataResponse.equals("success")) {
                    isLoading = false;
                    upToken("-1");
                } else {
                    toast(dataResponse);
                }
            }

            @Override
            public void onFail(String failMessage) {
                toast(failMessage);
                LoadingUtils.closeDialog();
            }

            @Override
            public void onError(Throwable e) {
                LoadingUtils.closeDialog();
            }
        });
    }

    /**
     * 获取用户及企业信息
     */
    private void getUserAnfCompanyInfo() {
        LoadingUtils.createLoadingDialog(this, "加载中...", true);
        if (comID.equals("-1")) {//从登录页进来先获取公司列表，拿到第0个的comID
            ExcitationPresenter.getInstance().getUserComAll(Globals.getToken(), new DataResponseListener<InfoArrayObject>() {
                @Override
                public void onSuccess(InfoArrayObject dataResponse) {
                    LoadingUtils.closeDialog();
                    companys.clear();
                    companys.addAll(dataResponse.getInfo());
                    if (companys.size() > 0) {
                        comID = companys.get(0).getComId();
                    }
                    getUserAnfCompanyInfo();
                }

                @Override
                public void onFail(String failMessage) {
                    LoadingUtils.closeDialog();
                }

                @Override
                public void onError(Throwable e) {
                    LoadingUtils.closeDialog();
                }
            });
        } else {
            ExcitationPresenter.getInstance().getUserAndComInfo(Globals.getToken(), comID, new DataResponseListener<UserObject>() {
                @Override
                public void onSuccess(UserObject userObjectdata) {
                    userObject = userObjectdata;
                    initData(userObject);
                    LoadingUtils.closeDialog();
                }

                @Override
                public void onFail(String failMessage) {
                    toast(failMessage);
                    LoadingUtils.closeDialog();
                }

                @Override
                public void onError(Throwable e) {
                    LoadingUtils.closeDialog();
                }
            });
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getUserAnfCompanyInfo();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (isOut) {
            Intent intent = new Intent(Globals.ACTION_FINISH_ALL_ACTIVITY);
            sendBroadcast(intent);
        }
    }
}
